﻿using DataAccess;
using DataAccess.Api;
using DataAccess.DAL;
using DataAccess.DTO;
using DataAccess.Models;
using LogUtility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Web.Controllers
{
    public class SysConfigController : BaseController
    {
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public JsonResult GetSysConfigs()
        {
            SysConfigDAL sysConfigDAL = new SysConfigDAL();

            string keyword = System.Web.HttpContext.Current.Request.Form["keyword"];
            int limit = XYD.Common.Request.GetFormInt("limit", 10);
            int offset = XYD.Common.Request.GetFormInt("offset", 1);

            string strWhere = " 1=1 ";
            string orderbys = "";

            strWhere += " and user_id=" + UserSession.user_id;

            if (!string.IsNullOrEmpty(keyword))
            {
                strWhere += string.Format(" and (name like '%{0}%' or domain like '%{0}%' )", keyword);
            }
            int count = 0;

            List<SysConfig> sysConfigs = sysConfigDAL.GetSysConfigs(strWhere, orderbys, limit, (offset / limit) + 1, out count);

            Result result = new Result();
            result.State = true;
            result.Message = "查询成功";
            result.Datas = new PageData<SysConfig> { Total = count, Rows = sysConfigs, PageIndex = (offset / limit) + 1, PageSize = limit };
            // return Json(new { State = true, Message = "查询成功", total = 
            //count, rows = sysConfigs });

            return Json(result);
        }

        public ActionResult Edit()
        {
            SysConfigDAL sysConfigDAL = new SysConfigDAL();

            var sysConfig = sysConfigDAL.GetSysConfigAllModel(UserSession.user_id);
            if (sysConfig == null)
            {
                sysConfig = new SysConfig_FlockManageDTO();
                sysConfig.def_flock_time = 10;
                sysConfig.def_send_time = 300;
                sysConfig.def_imgtext_time = 1;
                sysConfig.kick_type = "";
                sysConfig.def_pid = "";
                sysConfig.rate_all = 15;
                sysConfig.rate = 40;
                sysConfig.rate_i = 10;
                sysConfig.rate_ii = 5;

                sysConfig.send_format = @"{商品标题}
【推荐理由】{活动描述}
┄┄┄┄┄┄
原　价：【 {原价}】元
券后价：【 {券后价}】元
┄┄┄┄┄┄
复制这条消息, 打开【手机淘宝】即可购买{淘口令}＆{券连接}";
                sysConfig.welcome = "Hello，[NICKNAME]！欢迎您的加入！本群是福利群，群内直接输入 “搜索   产品名字”   如：搜索 衣服。可以领取淘宝天猫内部优惠券哦！";
               
                sysConfig.search_word = "搜索,有没有,买";
                sysConfig.kick_word = "广告,加我微信";
                sysConfig.domain = UserSession.user_name + ".f-9.cc";
                sysConfig.name = "优惠券汇总";

                sysConfig.auto_reply = @"你好=你好呀
*什么群=这是淘宝购物群
帮助=帮助 -打印此条帮助信息\r优惠 -全部特惠商品汇总网页地址\r搜索[关键词] -获取相关优惠产品汇总(命令有[搜索,有没有,买] 命令使用:买鞋子  有没有凉鞋   搜索饼干 任意一个命令都可以使用)\r亲~以上是可以使用的指令哦~
优惠=全网最低特价优惠汇总:http://" + sysConfig.domain + "/shop/{account}.html";


            }
            return View(sysConfig);
        }

        [HttpPost]
        public JsonResult Edit(FormCollection form)
        {
            dynamic obj = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(XYD.Common.Utils.UrlDecode(Request.Form.ToString()));

            SysConfigDAL SysConfigDAL = new SysConfigDAL();

            SysConfig sysConfig = new SysConfig();
            bool boo = false;

            if (int.Parse(obj.id.Value) != 0)
            {
                var configDto = SysConfigDAL.GetSysConfigAllModel(UserSession.user_id);
                sysConfig.add_data = configDto.add_data;
                sysConfig.promoter_id = UserSession.user_id;
                sysConfig.collecting_source_type = configDto.collecting_source_type;
                sysConfig.is_delete = configDto.is_delete;
                sysConfig.is_default = configDto.is_default;


                sysConfig.id = configDto.s_id;
                sysConfig.rate_all = int.Parse(obj.rate_all.Value);
                sysConfig.rate = int.Parse(obj.rate.Value);
                sysConfig.rate_i = int.Parse(obj.rate_i.Value);
                sysConfig.rate_ii = int.Parse(obj.rate_ii.Value);
                sysConfig.name = obj.name.Value;
                sysConfig.domain = obj.domain.Value;
                sysConfig.turing_key = obj.turing_key.Value;
                sysConfig.logo = obj.logo.Value;
                sysConfig.send_format = obj.send_format.Value;
                sysConfig.send_tail = obj.send_tail.Value;
                sysConfig.def_pid = obj.def_pid.Value;
                sysConfig.root_str = obj.root_str.Value;

                sysConfig.tkl_img = obj.tkl_img.Value;
                sysConfig.def_send_time = int.Parse(obj.def_send_time.Value);
                sysConfig.def_flock_time = int.Parse(obj.def_flock_time.Value);
                sysConfig.def_imgtext_time = int.Parse(obj.def_imgtext_time.Value);
                sysConfig.tb_open = obj.tb_open.Value;



                boo = SysConfigDAL.Update(sysConfig);
                if (boo)
                {
                    var response = new RobotApiHelper().UpdateSendtConfig(sysConfig.promoter_id.ToString());
                    //删除缓存
                    RedisHelper.Single_Remove_Itme(RedisKey.SysConfig_promoter_id(sysConfig.promoter_id.ToString()));
                    RedisHelper.Single_Remove_Itme(RedisKey.SysConfig(sysConfig.domain.ToString()));


                }
                if (boo)
                {
                    FlockManage fmModel = new FlockManage();
                    fmModel.id = configDto.fm_id;
                    fmModel.promoter_id = UserSession.user_id;
                    fmModel.auto_reply = obj.auto_reply.Value;
                    fmModel.kick_type = obj.kick_type.Value;
                    fmModel.kick_word = obj.kick_word.Value;
                    fmModel.search_word = obj.search_word.Value;
                    fmModel.welcome = obj.welcome.Value; ;

                    var fmBool = SysConfigDAL.Update<FlockManage>(fmModel);
                    if (fmBool)
                    {
                        var response = new RobotApiHelper().UpdateSysConfig(fmModel.promoter_id.ToString());
                        var res = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(XYD.Common.Utils.UrlDecode(response));
                        if (res.state != 1)
                        {
                            LogHelper.Warn(res);
                        }

                    }
                }


            }
            else
            {


                sysConfig.rate_all = int.Parse(obj.rate_all.Value);
                sysConfig.rate = int.Parse(obj.rate.Value);
                sysConfig.rate_i = int.Parse(obj.rate_i.Value);
                sysConfig.rate_ii = int.Parse(obj.rate_ii.Value);
                sysConfig.name = obj.name.Value;
                sysConfig.domain = obj.domain.Value;
                sysConfig.turing_key = obj.turing_key.Value;
                sysConfig.logo = obj.logo.Value;
                sysConfig.send_format = obj.send_format.Value;
                sysConfig.send_tail = obj.send_tail.Value;

                sysConfig.add_data = DateTime.Now;
                sysConfig.promoter_id = UserSession.user_id;

                sysConfig.tkl_img = obj.tkl_img.Value;
                sysConfig.def_send_time = int.Parse(obj.def_send_time.Value);
                sysConfig.def_flock_time = int.Parse(obj.def_flock_time.Value);
                sysConfig.def_imgtext_time = int.Parse(obj.def_imgtext_time.Value);
                sysConfig.tb_open = obj.tb_open.Value;
                sysConfig.def_pid = obj.def_pid.Value;
                sysConfig.root_str = obj.root_str.Value;

                sysConfig.is_default = 1;
                sysConfig.is_delete = 0;
                sysConfig.collecting_source_type = "1";


                boo = SysConfigDAL.Insert(sysConfig);
                if (boo)
                {
                    RedisHelper.Single_Remove_Itme(RedisKey.SysConfig_promoter_id(sysConfig.promoter_id.ToString()));
                    RedisHelper.Single_Remove_Itme(RedisKey.SysConfig(sysConfig.domain.ToString()));
                    try
                    {


                        var response = new RobotApiHelper().UpdateSendtConfig(sysConfig.promoter_id.ToString());
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Error("UpdateSendtConfig", ex);
                    }

                }

                if (boo)
                {
                    FlockManage fmModel = new FlockManage();
                    fmModel.promoter_id = UserSession.user_id;
                    fmModel.auto_reply = obj.auto_reply.Value;
                    fmModel.kick_type = obj.kick_type.Value;
                    fmModel.kick_word = obj.kick_word.Value;
                    fmModel.search_word = obj.search_word.Value;
                    fmModel.welcome = obj.welcome.Value; ;

                    var fmBool = SysConfigDAL.Insert<FlockManage>(fmModel);
                    if (fmBool)
                    {
                        try
                        {

                            var response = new RobotApiHelper().UpdateSysConfig(fmModel.promoter_id.ToString());
                            var res = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(XYD.Common.Utils.UrlDecode(response));
                            if (res.state != 1)
                            {
                                LogHelper.Warn(res);
                            }
                        }
                        catch (Exception ex)
                        {
                            LogHelper.Error("UpdateSysConfig", ex);
                        }

                    }
                }


            }

            return Json(new Result { State = boo, Message = boo ? "保存成功" : "保存失败", Datas = sysConfig.id });
        }
        /// <summary>
        /// 微信群列表
        /// </summary>
        /// <returns></returns>
        public ActionResult WxQunList()
        {
            return View();
        }
    }
}